﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CATcpClientSender
{
    public class MWinSerialPort
    {
        /// <summary>
        /// 模拟发送串口数据
        /// </summary>
        public static void SimulateSendPackage()
        {
            // 无线车次号
            string line = "0D D4 25 9F 0C 2B 00 3F 1F 00 00 1F 8C 30 20 03 03 03 20 20 20 54 05 0D 00 01 00 39 30 8E E8 61 96 00 00 39 30 64 00 0C 01 00 01 01 39 30 00 99 3B 00";
            // 心跳数据包
            line += "42 48 45 58 58 58 58 58 38 42 35 30 33 38 30 10 c5 46 78 89";
            // 心跳数据包
            line += "42 48 45 58 58 58 58 58 38 42 35 30 33 38 30 10 c5 46 78 89";

            line += "24 54 58 58 58 00 63 02 16 AC 60 02 16 AF 00 00 02 74 A4 24 47 50 47 47 41 2C 30 31 35 32 30 34 2E 30 30 2C 33 34 34 38 2E 36 30 33 35 31 33 33 33 2C 4E 2C 31 31 33 33 33 2E 31 39 32 33 35 30 36 30 2C 45 2C 32 2C 30 35 2C 35 2E 34 2C 31 31 39 2E 38 34 33 2C 4D 2C 2D 31 36 2E 32 34 37 2C 46 00 91";
            line += "24 47 50 47 47 41 2C 30 31 35 32 30 34 2E 30 30 2C 33 34 34 38 2E 36 30 33 35 31 33 33 33 2C 4E 2C 31 31 33 33 33 2E 31 39 32 33 35 30 36 30 2C 45 2C 32 2C 30 35 2C 35 2E 34 2C 31 31 39 2E 38 34 33 2C 4D 2C 2D 31 36 2E 32 34 37 2C 46";
            // 无线车次数据
            line += "24 54 58 58 58 00 47 02 16 AC 60 02 16 AF 00 00 01 98 A4 0D D4 25 9F 0C 2B 00 3F 1F 00 00 1F 8C 30 20 02 02 03 20 20 20 54 B8 22 00 01 00 39 30 00 09 3D 64 00 00 39 30 64 00 0C 01 00 01 01 39 30 00 33 58 00 00 61";

            // 心跳数据包
            //line += "42 48 45 58 58 58 58 58 38 42 35 30 33 38 30 10 c5 46 78 89";

            MatchCollection dexMatch = Regex.Matches(line, @"([0-9a-fA-Fa-f]{2})");

            byte[] data = new byte[dexMatch.Count];
            for (int i = 0; i < dexMatch.Count; i++)
            {
                data[i] = Convert.ToByte(dexMatch[i].Value, 16);
            }

            SendSerialPort(data);
        }
        #region 串口发送
        /// <summary>
        /// 串口发送
        /// </summary>
        /// <param name="bytelist"></param>
        public static void SendSerialPort(byte[] bytelist)
        {
            System.IO.Ports.SerialPort serial = new System.IO.Ports.SerialPort("COM3", 4800);

            serial.Open();
            serial.Write(bytelist, 0, bytelist.Length);


        }

        #endregion
    }
}
